package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Conclusion;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.ConclusionApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;


import java.util.List;
import java.util.stream.Collectors;
@Service
public class ConclusionApiImpl implements ConclusionApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoApi userInfoApi;

    @Override
    public List<Long> findSimilarYou(Long userId, String level, Integer score) {
        UserInfo userInfo = userInfoApi.findById(userId);
        Query query = new Query();
        Criteria criteria = new Criteria();
        Criteria criteriaOrA = new Criteria().norOperator(Criteria.where("userId").is(userId));
//        //且为异性
        Criteria criteriaOrB = new Criteria().norOperator(Criteria.where("gender").is(userInfo.getGender()));
//        //分数上下不超过2分
       Criteria criteriaOrC = new Criteria().andOperator(Criteria.where("score").lte(score + 3).gte(score - 3));
//        //最后将各组条件拼装至and中
       criteria.andOperator(criteriaOrA, criteriaOrB, criteriaOrC);
        //等级相同  //查询前10条*/
        query.addCriteria(Criteria.where("level").is(level)).with(Sort.by(Sort.Order.desc("created"))).limit(10);
        List<Conclusion> conclusionList = mongoTemplate.find(query, Conclusion.class);

        return conclusionList.stream().map(Conclusion::getUserId).collect(Collectors.toList());
    }

    @Override
    public void save(Conclusion conclusion) {
        Query query = new Query(Criteria.where("level").is(conclusion.getLevel()).and("userId").is(conclusion.getUserId()));
        if (!mongoTemplate.exists(query,Conclusion.class)){
            mongoTemplate.save(conclusion);
        }else {
            mongoTemplate.remove(query, Conclusion.class);
            mongoTemplate.save(conclusion);
        }

    }

    @Override
    public Conclusion queryReport(ObjectId id) {

        return mongoTemplate.findById(id,Conclusion.class);
    }

    @Override
    public Conclusion findConclusionList(Long userId, String level) {
        return mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId).and("level").is(level)),Conclusion.class);
    }
}
